package me.shurufa.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import me.shurufa.MainApplication;

/**
 * 通用工具类
 *
 * @FileName: me.shurufa.utils.Utils.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-14 12:28
 */
public class Utils {

  public static final int ONE_MINUTE = 60 * 1000;
  public static final int ONE_HOUR = 60 * 60 * 1000;
  public static final Charset CHARSET = Charset.forName("UTF-8");
  public static final int BUFFER_SIZE = 4096;

//long型时间工具类，如果是今天显示准确时间 如果不是今天显示日期

  public static String getDatetimeStr(long time) {
    Date date = new Date(time);
    if (isToday(date)) {
      return todayFormat.get().format(date);
    } else {
      return dateFormat.get().format(date);
    }
  }

  public static boolean isToday(Date date) {
    Calendar c1 = Calendar.getInstance();
    Calendar c2 = Calendar.getInstance();
    c2.setTime(date);
    return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2
            .get(Calendar.MONTH) && c1.get(Calendar.DAY_OF_MONTH) == c2
            .get(Calendar.DAY_OF_MONTH);
  }

  private static final ThreadLocal<DateFormat> todayFormat = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
      return new SimpleDateFormat("yyyy-MM-dd HH:mm");
    }
  };

  private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
      return new SimpleDateFormat("yyyy-MM-dd HH:mm");
    }
  };

  /**
   * 获取手机Imei码
   * 
   * @param context
   * @return
   */
  public static String getIMEI(Context context) {
    try {
      return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
          .getDeviceId();
    } catch (Exception e) {
      return "";
    }
  }

  /**
   * 读取文件流
   * 
   * @param inputStream
   * @return
   * @throws IOException
   */
  public static String readStream(BufferedInputStream inputStream) throws IOException {
    try {
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      byte[] buffer = new byte[BUFFER_SIZE];
      int count = 0;
      while ((count = inputStream.read(buffer)) > 0) {
        byteArrayOutputStream.write(buffer, 0, count);
      }
      return new String(byteArrayOutputStream.toByteArray(), CHARSET.name());
    } catch (Exception e) {
      return "";
    } catch (Error e) {
      return "";
    } finally {
      inputStream.close();
    }
  }

  /**
   * 关闭文件流
   * 
   * @param closeable
   */
  public static void closeQuietly(Closeable closeable) {
    try {
      if (closeable != null) {
        closeable.close();
      }
    } catch (Exception ignored) {

    }
  }

  public static void showToast(int resId) {
    Toast.makeText(MainApplication.getInstance(), resId, Toast.LENGTH_SHORT).show();
  }

  public static void showToast(String msg) {
    Toast.makeText(MainApplication.getInstance(), msg, Toast.LENGTH_SHORT).show();
  }

  public static int dp2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) ((dpValue * scale) + 0.5f);
  }

  public static Bitmap compressImageFromFile(String srcPath) {
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    newOpts.inJustDecodeBounds = true;//只读边,不读内容
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    float hh = 480f;//
    float ww = 320f;//
    int be = 1;
    if (w > h && w > ww) {
      be = (int) (newOpts.outWidth / ww);
    } else if (w < h && h > hh) {
      be = (int) (newOpts.outHeight / hh);
    }
    if (be <= 0)
      be = 1;
    newOpts.inSampleSize = be;//设置采样率

    newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//该模式是默认的,可不设
    newOpts.inPurgeable = true;// 同时设置才会有效
    newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收

    bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
//      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
    //其实是无效的,大家尽管尝试
    return bitmap;
  }

  public static String tranformDate(String string){
    String dateStr = "";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
      Date date = sdf.parse(string);
      dateStr = sdf.format(date);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    return dateStr;
  }
}
